from django.db import models
from datetime import datetime

class Device(models.Model):
    # 网关
    gateway = models.CharField(verbose_name="网关", max_length=32)
    # clientID
    client_id = models.CharField(verbose_name="client_id", max_length=64, unique=True)
    # 探头编号
    probe = models.CharField(verbose_name="探头", max_length=32)
    # 管件名称
    tube_name = models.CharField(verbose_name="管件名称", max_length=64)
    # 管件名义壁厚
    tube_nominal = models.FloatField(verbose_name="管件名义壁厚")
    # 管件材质
    tube_materail = models.CharField(verbose_name="管件材质", max_length=64, blank=True, null=True, default="304不锈钢")
    # 是否活动的
    is_active = models.BooleanField(verbose_name="是否在线", default=False)
    # 波形图
    wave = models.TextField(verbose_name="最新波形图", blank=True, null=True)
    # 闸门起始
    start = models.IntegerField(verbose_name="闸门起始位置", default=1000)
    # 闸门宽度
    width = models.IntegerField(verbose_name="闸门宽度", default=100)
    # 扫查范围
    scan_range = models.IntegerField(verbose_name="扫查范围", default=1792)
    # 探头增益
    gain = models.IntegerField(verbose_name="探头增益", default=350)
    # 板卡编号
    devicename = models.CharField(verbose_name="设备名", max_length=32)

    def __str__(self):
        return self.probe + '-' + self.tube_name

    class Meta:
        ordering = ['-gateway', '-devicename', '-probe']

# 监测数据的模型
class Mdata(models.Model):
    probe = models.CharField(verbose_name="设备名", max_length=32)
    thickness = models.FloatField(verbose_name="厚度")
    temperature = models.FloatField(verbose_name="温度")
    add_time = models.DateTimeField(verbose_name="添加时间", auto_now_add=True)

    def __str__(self):
        return str(self.thickness) + "mm"

    def to_dict(self):
        opts = self._meta
        data = {}
        for f in opts.concrete_fields:
            value = f.value_from_object(self)
            if isinstance(value, datetime):
                value = value.strftime('%Y-%m-%d %H:%M:%S')
            elif isinstance(f, models.FileField):
                value = value.url if value else None
            data[f.name] = value
        return data


